import React, { useEffect, useState } from "react"
import md5 from "js-md5"
import service from "@@/services/user.service"
import { Image, Text, View } from "@tarojs/components"
import { navigateTo, setStorage } from "@tarojs/taro"
import NavLayout from "@@/components/layout/nav.layout"
import TTabs from "@@/t-ui/tabs.tui"
import TInput from "@@/t-ui/input.tui"
import TButton from "@@/t-ui/button.tui"
import TDivider from "@@/t-ui/divider.tui"
import TToast from "@@/t-ui/toast.tui"
import "./login.scss"

let timer //定时器句柄
const phoneRegexp = /^[1][3,4,5,7,8][0-9]{9}$/

const Index = () => {
	const [current, setCurrent] = useState<number>(0) //当前tab值
	const [mobile, setMobile] = useState<string>("") //手机号
	const [passWord, setPassWord] = useState<string>("") //密码
	const [time, setTime] = useState<number>(0) //验证码倒计时
	const [verificationCode, setVerificationCode] = useState<string>("") //验证码
	const [isOpened, setIsOpened] = useState<boolean>(false) //轻提示开关
	const [toastMsg, setToastMsg] = useState<string>("") //轻提示内容
	useEffect(() => {
		const weixin_box = document.querySelector(".weixin_box") as HTMLElement
		var winHeight = window.innerHeight //获取当前页面高度
		var rangHeight //键盘的高度;滚动条位置；
		window.onresize = function () {
			var thisHeight = window.innerHeight //当前window高度
			rangHeight = winHeight - thisHeight
			if (rangHeight > 50) {
				// alert("滚动");
				//当软键盘弹出，在这里面操作
				weixin_box.style.display = "none"
			} else {
				//当软键盘收起，在此处操作
				// alert("键盘收起");
				weixin_box.style.display = "block"
			}
		}
		return () => {
			window.onresize = null
		}
	}, [])
	//跳转
	const goResetPwd = (url: string) => () => {
		if (TARO_ENV === "h5") {
			navigateTo({
				url
			})
		}
	}
	//去登录
	const goLogin = () => {
		if (TARO_ENV === "h5") {
			if (!phoneRegexp.test(mobile)) {
				openToast("请输入11位为数字的手机号")
				return false
			}
			let param = {
				mobile
			}
			if (current) {
				param['verificationCode'] = verificationCode
			} else {
				param['passWord'] = md5(passWord)
			}
			service.login(param).then(res => {
				if (res.code === 200) {
					setStorage({
						key: "token",
						data: res.data as string
					})
					openToast("登录成功")
					if (TARO_ENV === "h5") {
						navigateTo({
							url: "/pages/index/index"
						})
					}
				} else {
					openToast(res.msg)
				}
			})
		}
	}

	//发送验证码
	const sendVerificationCode = () => {
		if (TARO_ENV === "h5") {
			if (!phoneRegexp.test(mobile)) {
				openToast("请输入11-12位为数字的手机号")
				return false
			}
			service.sendVerificationCode({ mobile, type: 1 }).then(res => {
				if (res.code === 200) {
					countDown()
				} else {
					openToast(res.msg)
				}
			})
		}
	}
	//倒计时方法
	const countDown = () => {
		let num = 60
		setTime(num)
		const reduce = () => {
			if (num > 0) {
				timer = setTimeout(() => {
					num -= 1
					setTime(num)
					reduce()
				}, 1000)
			} else {
				clearTimeout(timer)
			}
		}
		reduce()
	}
	const openToast = (str: string) => {
		setToastMsg(str)
		setIsOpened(true)
		setTimeout(() => {
			setIsOpened(false)
		}, 500)
	}
	const changeMobile = (v) => {
		v = String(v)
		if (!phoneRegexp.test(v)) {
			v = v.substring(0, 11)
		}
		setMobile(v)
		return v
	}
	const paneList = [
		{
			content: (
				<View className={"form"}>
					<View className="input-item">
						<TInput
							border={false}
							name="mobile"
							maxlength={11}
							placeholder="手机号"
							onChange={changeMobile}
						/>
					</View>
					<View className="input-item">
						<TInput
							border={false}
							name="passWord"
							type="password"
							placeholder="密码"
							onChange={v => {
								setPassWord(v)
								return v
							}}
						/>
					</View>
				</View>
			)
		},
		{
			content: (
				<View className={"form"}>
					<View className="input-item">
						<TInput
							border={false}
							name="mobiles"
							maxlength={11}
							placeholder="手机号"
							onChange={changeMobile}
						/>
					</View>
					<View className="verify-code-box">
						<View className="input-item verify-code">
							<TInput
								border={false}
								name="verificationCode"
								type="text"
								placeholder="验证码"
								onChange={v => {
									setVerificationCode(v)
									return v
								}}
							/>
						</View>
						{time > 0 ? (
							<View className={"send"}>{time}</View>
						) : (
							<View className={"send"} onClick={sendVerificationCode}>
								发送验证码
							</View>
						)}
					</View>
				</View>
			)
		}
	]
	return (
		<NavLayout border leftIconType="chevron-left" color="#141414" id="LoginPage">
			<View className={"logo_view"}>
				<Image mode={"aspectFit"} src={require("@@/assets/img/login_logo.png")} />
			</View>
			<View className="form">
				<TTabs
					current={current}
					tabList={[{ title: "密码登录" }, { title: "短信登录" }]}
					paneList={paneList}
					onClick={val => {
						setCurrent(val)
					}}
				/>
				<View className="form-btn-login">
					<TButton type="primary" onClick={goLogin}>
						登录
					</TButton>
				</View>
				<View className={"other_box"}>
					<Text onClick={goResetPwd("/pages/resetPwd/resetPwd")}>忘记密码</Text>
					<Text>|</Text>
					<Text onClick={goResetPwd("/pages/register/register")}>注册</Text>
				</View>
				<View className={"weixin_box"}>
					<TDivider content="微信登录" />
					<View className={"weixin_view"}>
						<Image mode={"aspectFit"} src={require("@@/assets/img/weixin_logo.png")} />
					</View>
				</View>
			</View>
			<TToast isOpened={isOpened} text={toastMsg} />
		</NavLayout>
	)
}

export default Index
